<template>
    <div class="system-position-container">
        <el-form :inline="true" ref="form" class="system-search-form" :model="searchForm">
            <el-form-item>
                <el-input type="text" maxlength="100" v-model="searchForm.name" @keyup.enter.native="toFirstPage()" placeholder="职务名称" size="small"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="sub-btn" type="primary" size="small" @click="toFirstPage()">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="table-box">
            <el-button class="add-btn" type="primary" size="small" icon="el-icon-plus" v-auth="{code: 300008001001}" @click="showAddDialog">新增</el-button>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                @sort-change="sortChange"
                class="data-table">
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    width="50">
                </el-table-column>
                <el-table-column
                    prop="name"
                    align="center"
                    label="职务名称"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="remark"
                    align="center"
                    label="备注"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="createdName"
                    align="center"
                    label="创建人"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="createdTime"
                    align="center"
                    label="创建时间"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="启/停"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.state" size="small" :disabled="!showBtnAuth(300008001002)" @change="toChangeState(scope.$index, scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button type="text" size="small" v-auth="{code: 300008001002}" @click="tableEdit(scope.$index, scope.row)">
                            编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="getData"/>
        </div>
        <el-dialog
            :title="isAdd ? '新增职务' : '编辑职务'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            width="40%"
            center
            @close="closeDialog">
            <el-form :inline="false" ref="dialogForm" class="dialog-form" :rules="editFormRules" :model="editForm" label-width="80px">
                <el-form-item label="职务名称" prop="name">
                    <el-input type="text" maxlength="100" v-model="editForm.name" placeholder="请输入职务名称" size="small"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input type="textarea" maxlength="200" v-model="editForm.remarks" :rows="3" placeholder="请输入备注" size="small"></el-input>
                </el-form-item>
                <el-form-item label="启/停" class="switch-box" prop="status">
                    <el-switch v-model="editForm.status"></el-switch>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button type="primary" @click="submitEditForm('dialogForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getPositionList, addPosition, editPosition, changeState} from '@/api/system/position'
    import {showBtnAuth, getSortString} from '@/utils/filters'
    import Pagination from '@/components/Pagination'

    export default {
        name: 'index',
        data () {
            return {
                // 搜索表单
                searchForm: {
                    name: ''
                },
                departmentList: [],
                // 表格数据
                tableData: [],
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 10,
                // 表格高度
                tableHeight: 100,
                // 显示弹框
                dialogVisible: false,
                // 弹框表单
                editForm: {
                    name: '',
                    remarks: '',
                    status: true
                },
                // 是否是新增
                isAdd: true,
                // 排序字段
                sortMap: {},
                // 排序方式
                sortType: '',
                editFormRules: {
                    name: [
                        {required: true, message: '请填写职务名称', trigger: ['blur', 'change']}
                    ]
                },
                // 使用储存的数据，不去请求
                useStore: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
            this.tableHeight = height > 107 ? height : 107
            this.initData()
            this.getData()
        },
        mounted () {
            window.onresize = () => {
                // 213=其他元素高度60+50+48+55 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            showBtnAuth,
            /**
             * 初始化页面参数
             */
            initData () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (JSON.stringify(query) !== '{}') {
                    this.searchForm.name = query.keyword
                    this.currentPage = query.index || 1
                    this.pageSize = query.pageSize || 10
                    this.sortType = query.orderBy || null
                }
            },
            /**
             * 获取表格数据
             * @param type 是否重置页码
             */
            getData (type) {
                let params = {
                    keyword: this.searchForm.name,
                    index: this.currentPage,
                    size: this.pageSize
                }
                if (this.sortType) params.orderBy = this.sortType
                this.setGetStore(this.$route.name, params)
                if (this.getSession(this.$route.name, 'getPositionList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getPositionList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.total = res.data.total
                        this.sortMap = res.data.maps
                    }
                } else {
                    getPositionList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getPositionList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.total = res.data.total
                            this.sortMap = res.data.maps
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.getData()
            },
            /**
             * 修改条件后从第一页开始
             */
            toFirstPage () {
                this.currentPage = 1
                this.getData()
            },
            /**
             * 启动停止
             * @param index 索引
             * @param row 行数据
             */
            toChangeState (index, row) {
                let text = ''
                let title = ''
                if (row.state) {
                    text = `您确定启用"${row.name}"职务吗?`
                    title = '启用机构'
                } else {
                    text = `您确定停用"${row.name}"职务吗?停用后将不能再被使用!`
                    title = '停用机构'
                }
                this.$confirm(text, title, {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    this.changeIdState(row.id, row.state)
                }).catch(() => {
                    row.state = !row.state
                })
            },
            /**
             * 改变指定状态
             * @param id 数据id
             * @param state 状态
             */
            changeIdState (id, state) {
                let params = {
                    id: id,
                    state: state
                }
                changeState(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success(state ? '启用成功' : '停用成功')
                    } else if (res.code.toString() === '404') {
                        this.$message.error('未找到该职务')
                    } else {
                        this.$message.error(res.message)
                    }
                    this.getData()
                })
            },
            /**
             * 编辑表格内容
             * @param index 索引
             * @param row 行数据
             */
            tableEdit (index, row) {
                this.isAdd = false
                this.editForm = {
                    name: row.name,
                    status: row.state,
                    remarks: row.remark,
                    id: row.id
                }
                this.dialogVisible = true
            },
            /**
             * 关闭弹框
             */
            closeDialog () {
                this.editForm = {
                    name: '',
                    remarks: '',
                    status: true
                }
                this.$refs['dialogForm'].resetFields()
                this.dialogVisible = false
            },
            /**
             * 点击新增打开弹窗
             */
            showAddDialog () {
                this.isAdd = true
                this.dialogVisible = true
            },
            /**
             * 提交表单
             * @param formName 表单名
             */
            submitEditForm (formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params = {
                            name: this.editForm.name,
                            remark: this.editForm.remarks,
                            state: this.editForm.status
                        }
                        if (this.isAdd) {
                            addPosition(params).then(res => {
                                if (res.code.toString() === '200') {
                                    this.$message.success('新增成功')
                                    this.closeDialog()
                                    this.getData()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        } else {
                            params.id = this.editForm.id
                            editPosition(params).then(res => {
                                if (res.code.toString() === '200') {
                                    this.$message.success('保存成功')
                                    this.closeDialog()
                                    this.getData()
                                } else {
                                    this.$message.error(res.message)
                                }
                            })
                        }
                    } else {
                        return false
                    }
                })
            }
        },
        components: {
            Pagination
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .system-position-container {
        .system-search-form {
            .el-form-item {
                margin-bottom: 0;
            }
        }
        .table-box {
            background: #fff;
            padding: 10px;
            box-sizing: border-box;
            height: calc(100vh - 183px);
            .add-btn {
                margin-bottom: 10px;
            }
        }
        /deep/.el-dialog {
            width: 800px!important;
            .el-dialog__body {
                padding: 10px;
                .dialog-form {
                    width: 90%;
                    margin: 0 auto;
                    .el-form-item {
                        .el-input {
                            width: 220px;
                        }
                    }
                }
            }
            .el-dialog__footer {
                text-align: right;
            }
        }
    }
</style>
